import 'dart:convert';
import 'dart:io';

class IntlSocketServer {
  final Set<WebSocket> _webSockets = {};

  static final IntlSocketServer instance = IntlSocketServer();

  void run() async {
    HttpServer server = await HttpServer.bind('127.0.0.1', 18928);
    print('Socket Server running on: ${server.address.address}:${server.port}');

    await for (HttpRequest request in server) {
      if (WebSocketTransformer.isUpgradeRequest(request)) {
        WebSocket socket = await WebSocketTransformer.upgrade(request);
        socket.add('Hello, world!');
        if (request.uri.path == '/find/strings') {
          continue;
        }

        _webSockets.add(socket);

        socket.listen(
          (event) {
            //
          },
          onDone: () {
            _webSockets.remove(socket);
          },
          onError: (error) {
            _webSockets.remove(socket);
          },
          cancelOnError: true,
        );
      }
    }
  }

  void postEvent(Map<String, String> event) {
    final string = jsonEncode(event);

    for (var element in _webSockets) {
      element.add(string);
    }
  }
}
